package com.gnerv.author.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gnerv.author.entity.User;
import com.gnerv.author.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * @description: 授权验证
 * @author: Gnerv LiGen
 * @date: 2018-05-18
 **/
@Component
public class ShiroUserRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> strings = new HashSet<>();
        strings.add("blog:article");
        strings.add("blog:catalog");
        strings.add("blog:config");
        strings.add("blog:user");
        strings.add("blog:login:user");
        strings.add("blog:commentary:update");
        strings.add("blog:commentary:delete");
        info.setStringPermissions(strings);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String account = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        // 查询用户信息
        User user = userService.selectUser(new User(account, password));
        // 账号或者密码错误
        if (StringUtils.isEmpty(user)) {
            throw new UnknownAccountException("账号或者密码错误！");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }

}
